<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <!--
      指定网页的兼容性模式设置,IE使用最新的引擎渲染网页，chrome=1则可以激活Chrome Frame
    -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge, Chrome=1" />
    <title>document</title>
  </head>

  <body>
    <div>数字: <input type="number" id="num" /></div>
    <div>进制: <input type="number" id="progressive" max="16" min="2" /></div>
    <button id="btn">进制转换</button>
    <p id="numConversion"></p>
    <script>
      // 进制转换
      function progressiveConversion(num, progress = 2) {
        // 存放的栈
        var conversionArr = []
        var digits = '0123456789ABCDEF'
        // 输出进制转换后的数
        var progressStr = ''
        while (num > 0) {
          conversionArr.push(num % progress)
          num = Math.floor(num / progress)
        }
        while (conversionArr.length !== 0) {
          progressStr += digits[conversionArr.pop()]
        }
        return progressStr
      }

      function ready(fn) {
        if (
          document.attachEvent
            ? document.readyState === 'complete'
            : document.readyState !== 'loading'
        ) {
          fn()
        } else {
          document.addEventListener('DOMContentLoaded', fn)
        }
      }

      ready(function() {
        var btn = document.getElementById('btn')
        var int = document.getElementById('num')
        var progressive = document.getElementById('progressive')
        var numConversion = document.getElementById('numConversion')
        btn.addEventListener('click', function() {
          var progressiveVal = progressive.value
          if (progressiveVal < 2 || progressiveVal > 16) {
            alert('请输入正确的进制！')
            return false
          }
          numConversion.innerHTML = progressiveConversion(
            int.value,
            progressiveVal
          )
        })
      })
    </script>
  </body>
</html>
